<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '修改运费模板' : '新增运费模板' }}</span>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="快递公司名称" prop="expressCompany">
              <el-input v-model="form.expressCompany" placeholder="请输入快递公司名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="快递公司编码" prop="expressCode">
              <el-input v-model="form.expressCode" placeholder="请输入快递公司编码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="计费方式" prop="calculationMethod">
              <el-input v-model="form.calculationMethod" placeholder="请输入计费方式" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="首重/首件" prop="firstWeight">
              <el-input v-model="form.firstWeight" placeholder="请输入首重/首件" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="首重/首件费用" prop="firstFee">
              <el-input-number v-model="form.firstFee" :precision="2" :min="0" placeholder="请输入首重/首件费用" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="续重/续件" prop="additionalWeight">
              <el-input v-model="form.additionalWeight" placeholder="请输入续重/续件" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="续重/续件费用" prop="additionalFee">
              <el-input-number v-model="form.additionalFee" :precision="2" :min="0" placeholder="请输入续重/续件费用" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="包装费" prop="packagingFee">
              <el-input-number v-model="form.packagingFee" :precision="2" :min="0" placeholder="请输入包装费" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="免邮金额" prop="freeShippingAmount">
              <el-input-number v-model="form.freeShippingAmount" :precision="2" :min="0" placeholder="请输入免邮金额" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="是否默认模板" prop="isDefault">
              <el-select v-model="form.isDefault" placeholder="请选择是否默认" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.ec_currect_and_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 配送区域 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="配送区域" prop="deliveryAreas">
              <div v-for="(area, index) in deliveryAreasList" :key="index" style="margin-bottom: 10px; display: flex; align-items: center;">
                <el-input 
                  v-model="deliveryAreasList[index]" 
                  placeholder="请输入配送区域" 
                  style="flex: 1; margin-right: 10px;"
                />
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  size="small" 
                  @click="removeDeliveryArea(index)"
                  :disabled="deliveryAreasList.length === 1"
                >删除</el-button>
              </div>
              <el-button type="primary" icon="el-icon-plus" size="small" @click="addDeliveryArea">添加配送区域</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 备注 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getTemplate, addTemplate, updateTemplate } from "@/api/system/template"

export default {
  name: "TemplateForm",
  dicts: ['sys_common_status', 'ec_currect_and_no'],
  data() {
    return {
      // 提交状态
      loading: false,
      // 是否为编辑模式
      isEdit: false,
      // 配送区域列表
      deliveryAreasList: [''],
      // 表单参数
      form: {
        templateId: null,
        templateName: null,
        expressCompany: null,
        expressCode: null,
        calculationMethod: null,
        firstWeight: null,
        firstFee: null,
        additionalWeight: null,
        additionalFee: null,
        packagingFee: null,
        freeShippingAmount: null,
        deliveryAreas: null,
        isDefault: "0",
        status: "0",
        remark: null
      },
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        expressCompany: [
          { required: true, message: "快递公司名称不能为空", trigger: "blur" }
        ],
        firstFee: [
          { required: true, message: "首重/首件费用不能为空", trigger: "blur" }
        ],
        additionalFee: [
          { required: true, message: "续重/续件费用不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    const pageType = this.$route.query.pageType
    const templateId = this.$route.query.templateId
    if (pageType === 'edit' && templateId) {
      this.isEdit = true
      this.getTemplateInfo(templateId)
    }
  },
  methods: {
    /** 获取运费模板详细信息 */
    getTemplateInfo(templateId) {
      getTemplate(templateId).then(response => {
        this.form = response.data
        // 解析配送区域到列表
        if (this.form.deliveryAreas) {
          this.deliveryAreasList = this.parseDeliveryAreas(this.form.deliveryAreas)
          if (this.deliveryAreasList.length === 0) {
            this.deliveryAreasList = ['']
          }
        } else {
          this.deliveryAreasList = ['']
        }
      })
    },
    /** 解析配送区域JSON字符串为数组 */
    parseDeliveryAreas(deliveryAreas) {
      if (!deliveryAreas) return []
      try {
        const areas = JSON.parse(deliveryAreas)
        return Array.isArray(areas) ? areas : []
      } catch (e) {
        return deliveryAreas.split(',').filter(area => area.trim())
      }
    },
    /** 添加配送区域 */
    addDeliveryArea() {
      this.deliveryAreasList.push('')
    },
    /** 删除配送区域 */
    removeDeliveryArea(index) {
      if (this.deliveryAreasList.length > 1) {
        this.deliveryAreasList.splice(index, 1)
      }
    },
    /** 表单重置 */
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        expressCompany: null,
        expressCode: null,
        calculationMethod: null,
        firstWeight: null,
        firstFee: null,
        additionalWeight: null,
        additionalFee: null,
        packagingFee: null,
        freeShippingAmount: null,
        deliveryAreas: null,
        isDefault: "0",
        status: "0",
        remark: null
      }
      this.deliveryAreasList = ['']
      this.resetForm("form")
    },
    /** 取消按钮 */
    cancel() {
      this.$tab.closePage()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          // 将配送区域列表转换为JSON字符串
          const validAreas = this.deliveryAreasList.filter(area => area.trim())
          this.form.deliveryAreas = JSON.stringify(validAreas)
          
          if (this.form.templateId != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.loading = false
              this.$tab.closePage()
            }).catch(() => {
              this.loading = false
            })
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.loading = false
              this.$tab.closePage()
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>